package org.eenie.appseed.ui.form

import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.nobody.api.cache.ApiCache
import com.nobody.api.cache.model.Strategy
import org.eenie.appseed.databinding.ActivityFormBinding
import org.eenie.appseed.net.api.IndexApi
import org.eenie.core.base.viewbinding.BaseBindingActivity
import org.eenie.core.ext.launchWithDialog
import org.eenie.core.ext.onClick
import java.text.SimpleDateFormat
import kotlin.time.DurationUnit

class FormActivity : BaseBindingActivity<ActivityFormBinding>() {

    private val mApi by lazy { IndexApi() }


    override fun initUI() {

        binding.btnLoad.onClick {
            fetchBannerList()
        }


        binding.btnClear.onClick {
            ApiCache.clear()
            binding.tvData.text = "缓存数据："
            binding.tvExpired.text = "过期时间："
            binding.tvSource.text = "缓存来源："
            updateCacheInfo()
        }


        fetchBannerList()
    }

    override fun providerBinding() = ActivityFormBinding.inflate(layoutInflater)


    private fun fetchBannerList() {
        lifecycleScope.launchWithDialog {
            CacheService.fetchBanner()
                .connectProvider(mApi::fetchBanner)
                .cacheStrategy(Strategy.CACHE_FIRST)
                .expireTime(30, DurationUnit.SECONDS)
                .verifyCache(true)
                .launch {
                    LogUtils.e("${it.source}")
                    binding.tvSource.text = "缓存来源：${it.source}"
                    binding.tvExpired.text = "过期时间：${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(it.expireTime)}"
                    binding.tvData.text = "缓存数据：\n${it.data}"
                    updateCacheInfo()
                }
        }
    }

    private fun updateCacheInfo() {
        val size = ApiCache.size()
        val maxSize = ApiCache.maxSize()
        binding.tvSize.text = "缓存大小：$size/$maxSize"
    }


}